package com.zcxy360.sandtable.util;

import java.io.File;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.springframework.web.multipart.MultipartFile;

public class UploadUtil {

	private static final String PDF_TYPE = ".pdf";
	private static final List<String> IMG_TYPE = Arrays.asList(".jpg", ".gif", ".bmp", ".png", ".jpeg", ".ico");
	private static final List<String> VIDEO_TYPE = Arrays.asList(".mp4", ".rmvb", ".avi", ".wmv", ".3gp", ".mkv",
			".flv");
	private static final String IMG_PATH = "E:/res/sandtable/upload/img/";
	private static final String PDF_PATH = "E:/res/sandtable/upload/pdf/";
	private static final String VIDEO_PATH = "E:/res/sandtable/upload/video/";

	private static final DiskFileItemFactory FACTORY = new DiskFileItemFactory();
	static {
		FACTORY.setSizeThreshold(10 * 1024 * 1024);
		File f = new File(IMG_PATH);
		f.mkdirs();
		f = new File(PDF_PATH);
		f.mkdirs();
		f = new File(VIDEO_PATH);
		f.mkdirs();
	}


	public static void uploadImg(HttpServletRequest request, ServletFileUpload fileUpload, FileItem item, String type,
			List<String> paths) throws Exception {
		fileUpload.setSizeMax(10 * 1024 * 1024);
		String fileName = UUID.randomUUID() + type;
		String filePath = IMG_PATH + fileName;
		File file = new File(filePath);
		file.createNewFile();
		item.write(file);
		paths.add(filePath.replace("E:/res", "/res"));
	}

	public static String uploadPdf(MultipartFile file) {
		String type = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".")).toLowerCase();
		if (!PDF_TYPE.contains(type)) {
			throw new RuntimeException("pdf格式不正确");
		}
		String path;
		try {
			path = PDF_PATH + UUID.randomUUID() + type;
			file.transferTo(new File(path));
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException("上传失败");
		}
		return path;
	}

	public static String uploadVideo(MultipartFile file) {
		String type = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".")).toLowerCase();
		if (!VIDEO_TYPE.contains(type)) {
			throw new RuntimeException("视频格式不正确");
		}
		String path;
		try {
			path = VIDEO_PATH + UUID.randomUUID() + type;
			file.transferTo(new File(path));
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException("上传失败");
		}
		return path;
	}

}
